package jpao.benchmark.metric;

/**
 *
 * @author soa
 */
public class Unit {

    public static final String CENTER_DOT = ".";
    public static final String SOLIDUS = "/";
    public static final String PER = " per ";
    
    public static final Unit TRANSACTION_UNIT = new Unit("Transaction", "tx");
    
    // time units
    public static final Unit NANOSECOND_UNIT = new Unit("nanosecond", "ns");
    public static final Unit MICROSECOND_UNIT = new Unit("microsecond", "µs");
    public static final Unit MILLISECOND_UNIT = new Unit("milliosecond", "ms");
    public static final Unit SECOND_UNIT = new Unit("second", "s");
    
    private String name;
    private String symbol;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSymbol() {
        return symbol;
    }

    public void setSymbol(String symbol) {
        this.symbol = symbol;
    }

    public Unit(String name, String symbol) {
        this.name = name;
        this.symbol = symbol;
    }

    private Unit deriveTo(Unit unit, boolean multiply) {

        // the new symbol
        StringBuilder symbolBuilder = new StringBuilder(symbol);
        if (multiply) {
            symbolBuilder.append(CENTER_DOT);
        } else {
            symbolBuilder.append(SOLIDUS);
        }
        symbolBuilder.append(unit.getSymbol());

        // the new name
        StringBuilder nameBuilder = new StringBuilder(name);
        if (!multiply) {
            nameBuilder.append(PER);
        }
        nameBuilder.append(unit.getName());

        return new Unit(nameBuilder.toString(), symbolBuilder.toString());
    }

    public Unit multiply(Unit unit) {
        return deriveTo(unit, true);
    }

    public Unit divide(Unit unit) {
        return deriveTo(unit, false);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (getClass() != obj.getClass()) {
            return false;
        }
        final Unit other = (Unit) obj;
        if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) {
            return false;
        }
        if ((this.symbol == null) ? (other.symbol != null) : !this.symbol.equals(other.symbol)) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 7;
        hash = 17 * hash + (this.name != null ? this.name.hashCode() : 0);
        hash = 17 * hash + (this.symbol != null ? this.symbol.hashCode() : 0);
        return hash;
    }

    @Override
    public String toString() {
        return "Unit{" + "name=" + name + ", symbol=" + symbol + '}';
    }
    
    
}
